package com.yh.csx.crm.core.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

public class FileUtils {
    private static final String tmpdir = getTempDir();

    private static String getTempDir() {
        String dir = System.getProperty("java.io.tmpdir");
        if (dir == null) {
            dir = "tmp";
        }
        try {
            dir = new File(dir).getCanonicalPath();
        } catch (Exception e) {
        }
        return dir;
    }

    public static String getTempPath() {
        return tmpdir;
    }

    public static File getTempFile() {
        return new File(tmpdir);
    }

    public static File createTempDirectory(String dirName) throws IOException {
        File dir = dirName == null ? new File(tmpdir) : new File(tmpdir + "/" + dirName);
        if (!dir.exists() && !dir.mkdirs()) {
            throw new IOException("create temp dir failed: " + dir);
        }
        return dir;
    }

    public static File randomTempDirectory() throws IOException {
        return Files.createTempDirectory(null).toFile();
    }

    public static File createTempFile(String dirName, String fileName) throws IOException {
        File dir = createTempDirectory(dirName);
        return new File(dir.getPath() + "/" + fileName);
    }

    public static File createTempFile(String fileName) throws IOException {
        return createTempFile(null, fileName);
    }

    public static File randomTempFile(String dirName, String suffix) throws IOException {
        String fileName = UUID.randomUUID().toString().replace("-", "");
        if (suffix.startsWith(".")) {
            fileName += suffix;
        } else {
            fileName += "." + suffix;
        }
        return createTempFile(dirName, fileName);
    }

    public static File randomTempFile(String suffix) throws IOException {
        return randomTempFile(null, suffix);
    }

}
